package io.youngledo.usb;

import io.youngledo.usb.ui.ExceptionDialog;
import io.youngledo.usb.ui.ExceptionListDialog;
import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Duration;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通知和用户反馈管理器
 * 提供多种类型的用户反馈机制
 */
@Slf4j
public class NotificationManager {

    @Setter
    private VBox notificationArea;
    private Stage parentStage;
    private ExceptionListDialog exceptionListDialog;
    private Button errorButton; // 状态栏错误按钮
    private boolean ownerSet = false; // 标记是否已设置 owner

    public void setParentStage(Stage parentStage) {
        this.parentStage = parentStage;
        this.exceptionListDialog = new ExceptionListDialog();
        // 设置清空回调，用于更新错误按钮状态
        exceptionListDialog.setOnClearCallback(this::updateErrorButton);
        // initOwner() 将在显示对话框时调用
    }

    /// 设置状态栏错误按钮
    ///
    public void setErrorButton(Button errorButton) {
        this.errorButton = errorButton;
        if (errorButton != null) {
            errorButton.setVisible(false); // 初始隐藏
            errorButton.setOnAction(e -> showExceptionList());
            errorButton.setTooltip(new Tooltip("查看异常列表"));
        }
    }

    /**
     * 显示成功消息
     */
    public void showSuccess(String message) {
        showInlineNotification(message, NotificationType.SUCCESS);
    }

    /**
     * 显示信息消息
     */
    public void showInfo(String message) {
        showInlineNotification(message, NotificationType.INFO);
    }

    /**
     * 显示警告消息
     */
    public void showWarning(String message) {
        showInlineNotification(message, NotificationType.WARNING);
    }

    /**
     * 显示错误消息
     */
    public void showError(String message) {
        showInlineNotification(message, NotificationType.ERROR);
    }

    /**
     * 显示内联通知
     */
    private void showInlineNotification(String message, NotificationType type) {
        if (notificationArea == null) {
            return;
        }

        // 创建通知标签
        Label notificationLabel = new Label(message);
        notificationLabel.setWrapText(true);
        notificationLabel.setPadding(new Insets(10));
        notificationLabel.setMaxWidth(Double.MAX_VALUE);

        // 设置样式类
        switch (type) {
            case SUCCESS:
                notificationLabel.getStyleClass().add("notification-success");
                break;
            case INFO:
                notificationLabel.getStyleClass().add("notification-info");
                break;
            case WARNING:
                notificationLabel.getStyleClass().add("notification-warning");
                break;
            case ERROR:
                notificationLabel.getStyleClass().add("notification-error");
                break;
        }

        // 添加到通知区域
        javafx.application.Platform.runLater(() -> {
            notificationArea.getChildren().add(notificationLabel);

            // 自动淡出效果
            FadeTransition fadeOut = new FadeTransition(Duration.seconds(0.5), notificationLabel);
            fadeOut.setFromValue(1.0);
            fadeOut.setToValue(0.0);
            fadeOut.setDelay(Duration.seconds(3)); // 3秒后开始淡出
            fadeOut.setOnFinished(e -> notificationArea.getChildren().remove(notificationLabel));
            fadeOut.play();
        });
    }

    /// 记录异常到异常列表
    ///
    private void recordException(String title, String message, Throwable throwable) {
        if (exceptionListDialog != null) {
            exceptionListDialog.addException(title, message, throwable);
            updateErrorButton();
        }
    }

    /// 显示异常列表
    ///
    public void showExceptionList() {
        if (exceptionListDialog != null) {
            // 只在第一次显示时设置 owner
            if (!ownerSet && parentStage != null) {
                exceptionListDialog.initOwner(parentStage);
                ownerSet = true;
            }
            exceptionListDialog.showDialog();
        }
    }

    /// 更新错误按钮状态
    ///
    private void updateErrorButton() {
        if (errorButton != null && exceptionListDialog != null) {
            int count = exceptionListDialog.getExceptionCount();
            Platform.runLater(() -> {
                if (count > 0) {
                    errorButton.setVisible(true);
                    errorButton.setText("⚠️ " + count);
                    errorButton.setTooltip(new Tooltip("发现 " + count + " 个异常，点击查看"));
                } else {
                    errorButton.setVisible(false);
                }
            });
        }
    }

    /**
     * 处理存储异常并记录到异常列表
     */
    public void handleStorageException(Throwable e, String operation) {
        String errorMessage;

        // 根据异常类型提供更友好的错误信息
        String message = e.getMessage() != null ? e.getMessage().toLowerCase() : "";
        if (message.contains("connection") || message.contains("connect")) {
            errorMessage = "连接失败，请检查网络设置";
        } else if (message.contains("permission") || message.contains("access")) {
            errorMessage = "权限不足，请检查访问权限";
        } else if (message.contains("not found") || message.contains("404")) {
            errorMessage = "资源不存在";
        } else if (message.contains("timeout")) {
            errorMessage = "操作超时，请稍后重试";
        } else if (message.contains("bucket")) {
            errorMessage = "存储桶操作失败";
        } else {
            errorMessage = "操作失败，请稍后重试";
        }

        // 记录到异常列表，不自动弹出对话框
        recordException(operation + " 失败", errorMessage, e);

        // 在状态栏显示简短提示
        showError(errorMessage);

        // 详细的异常信息输出到日志
        log.error("Storage operation '{}' failed", operation, e);
    }

    /**
     * 通知类型枚举
     */
    private enum NotificationType {
        SUCCESS, INFO, WARNING, ERROR
    }
}